<?php

namespace App\Console\Commands;

use App\Models\MemberOther;
use App\Models\Order;
use App\Models\OrderRemark;
use App\Models\OrderLease;
use App\Models\OrderGoods;
use App\Models\Goods;
use App\Models\GoodsSetmeal;
use App\Models\GoodsSpec;
use App\Models\AuthenticLog;
use App\Models\OtherOrder;
use App\Services\GoodsService;
use App\Services\RadarService;
use App\Services\OrderService;
use App\Services\AlipayService;
use App\Services\YpcreditService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Models\OtherOrderAllocate;
class OtherOrderSyncCommand extends BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'otherOrderSync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '外部订单同步任务';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    protected function handleExec()
    {


        $res = RadarService::getOtherOrder();
      // dd(COUNT($res['data']));
        if($res['status']){ //成功
            foreach($res['data'] as $data){
                //请求订单数量
                $order_count = COUNT($res['data']);
                $order_data = json_decode($data['order_data'],true);

                  if(Redis::get('TradeNo'.$order_data['trade_no'])){
                     continue;
                  }

                $member_data = json_decode($data['member_data'],true);
                if(isset($member_data['cert_no'])&&$member_data['cert_no']){
                    $age=getAgeByID($member_data['cert_no']);
                    if($age<18||$age>40){
                        RadarService::setOtherOrder($order_count,$order_data['id']);
                        continue;
                    }
                }

//                $otherMember=OtherOrderAllocate::whereRaw('weight > timecate')->orderBy('id', 'desc')->first();
//                $otherMember = obToArray($otherMember);
//
//
//                $order_data['begin_time'] = date('Y-m-d H:i:s');
//                $order_data['end_time'] = date('Y-m-d H:i:s',strtotime('+ '.$order_data['month_total'].'month'));
//                if(empty($otherMember)){
//                    OtherOrderAllocate::where('timecate','>',0)->update(['timecate'=>0]);
//                    $otherMember=OtherOrderAllocate::whereRaw('weight > timecate')->orderBy('id', 'desc')->first();
//                    $otherMember = obToArray($otherMember);
//                }
//
//                $open_goods_member=OtherOrderAllocate::whereRaw('open_weight > open_weight_timecate')->where('open_goods',1)->orderBy('id', 'desc')->first();//租机订单优选推送
//                $open_goods_member = obToArray($open_goods_member);
//                if(empty($open_goods_member)){
//                    OtherOrderAllocate::where('open_weight','>',0)->update(['open_weight_timecate'=>0]);
//                    $open_goods_member=OtherOrderAllocate::whereRaw('open_weight > open_weight_timecate')->where('open_goods',1)->orderBy('id', 'desc')->first();//租机订单优选推送
//                    $open_goods_member = obToArray($open_goods_member);
//                }
//                if(isset($order_data['is_latest_performance_time'])&&$order_data['is_latest_performance_time']==1&&$open_goods_member){
//
//                   $otherMember=OtherOrderAllocate::where('member_id',$open_goods_member['member_id'])->orderBy('id', 'desc')->first();
//                     $OtherOrder=[
//                         'order_data'=>json_encode($order_data),
//                         'order_lease_data'=>$data['order_lease_data'],
//                         'goods_data'=>$data['goods_data'],
//                         'member_data'=>$data['member_data'],
//                         'remark_data'=>$data['remark_data'],
//                         'member_id'=>$otherMember['member_id'],
//                         'order_id'=>$order_data['id'],
//                         'status'=>1,
//                         'is_allocate'=>1,
//                         'is_open_success'=>1
//                     ];
//                     OtherOrder::create($OtherOrder);
////                     OtherOrderAllocate::where('id',$otherMember['id'])->increment('timecate');
//                     OtherOrderAllocate::where('id',$otherMember['id'])->increment('open_weight_timecate');
//                    $isSendOther=$otherMember['member_id']?1:0;
//                }else if($order_data&&$otherMember){
//                    if($otherMember['limit']){
//                        $order_limit_count=OtherOrder::where('member_id',$otherMember['member_id'])->whereDate('created_at', date('Y-m-d'))->count();
//                        if($order_limit_count>=$otherMember['limit']){
//                            $otherMember=OtherOrderAllocate::whereRaw('limit = 0')->first();
//                        }
//                    }
                    $otherMember=OtherOrderAllocate::where('id',6)->first();
                    $OtherOrder=[
                        'order_data'=>json_encode($order_data),
                        'trade_no'=>$order_data['trade_no'],
                        'order_lease_data'=>$data['order_lease_data'],
                        'goods_data'=>$data['goods_data'],
                        'member_data'=>$data['member_data'],
                        'remark_data'=>$data['remark_data'],
                        'member_id'=>$otherMember['member_id'],
                        'order_id'=>$order_data['id'],
                        'status'=>1,
                        'is_allocate'=>1
                    ];
                    OtherOrder::create($OtherOrder);
                    OtherOrderAllocate::where('id',$otherMember['id'])->increment('timecate');
                    $isSendOther=$otherMember['member_id']?1:0;
//               }

//                dd($isSendOther);
                $otherMember && OtherOrderAllocate::where('id',$otherMember['id'])->increment('totalcate');

                $order_lease_datas = json_decode($data['order_lease_data'],true);
                $goods_data = json_decode($data['goods_data'],true);
                $member_data = json_decode($data['member_data'],true);
                $remark_data = json_decode($data['remark_data'],true);
               // dd($order_lease_datas);

            // if(!empty($order_data) && !empty($order_lease_datas) && !empty($goods_data) && !empty($member_data)){
            if(!empty($order_data) && !empty($goods_data) && !empty($member_data)){
                $this->upload_img($order_data['imgurl']);
                $this->upload_img($member_data['idcard_front']);
                $this->upload_img($member_data['idcard_back']);

//                dd($order_lease_datas);
                //会员资料
                $cert_no = $member_data['cert_no'];
                $member = MemberOther::where('cert_no',$cert_no)->select('id')->first();
                $member = obToArray($member);
                if($member){
                    $uid = $member['id'];
                }else{

                    $add_member_data = [
                        'mobile'=>$member_data['mobile'],
                        'user_id'=>isset($member_data['user_id'])?$member_data['user_id']:0,
                        'cert_name'=>$member_data['cert_name'],
                        'cert_no'=>$cert_no,
                        'idcard_front'=>$member_data['idcard_front'],
                        'idcard_back'=>$member_data['idcard_back'],
                        'head_image'=>$member_data['head_image'],
                        'nick_name'=>$member_data['nick_name'],
                        'gender'=>$member_data['gender'],
                        'province'=>$member_data['province'],
                        'city'=>$member_data['city'],
                        'status'=>'1',
                        'create_time'=>time(),
                        'update_time'=>time()
                    ];
                    //ceshi123
                    $uid = MemberOther::insertGetId($add_member_data);//会员ID
                }
                $goods_detail = $goods_data['goods'];
                // dd($goods_detail);
                $goods_setmeal_detail = $goods_data['goods_setmeal'];
                $goods_spec_details = $goods_data['goods_spec'];

                // $goods_title = $goods_detail['title'];
                // $goods = Goods::where('title',$goods_title)->select('id')->first();
                // $goods = obToArray($goods);
                // if($goods){
                //     $goods_id = $goods['id'];
                // }else{
                    //商品
                    $add_goods_data = [
                        'title'=>$goods_detail['title'],
                        'new_grade'=>$goods_detail['new_grade'],
                        'member_id'=>'1678175782',
                        'category_id'=>'0',
                        'status'=>'2',
                        'pay_type'=>'1',
                        'ischeck'=>'4',
                        'is_delete'=>'1',
                        'create_time'=>time(),
                        'update_time'=>time(),
                        'is_show'=>'2'
                    ];
                    //ceshi123
                    $goods_id = Goods::insertGetId($add_goods_data);//商品ID
                // }
                //商品套餐
                $add_goods_setmeal_data = [
                    'goods_id'=>$goods_id,
                    'title'=>$goods_setmeal_detail['title'],
                    'quantity'=>$goods_setmeal_detail['quantity'],
                    'foregift'=>$goods_setmeal_detail['foregift'],
                    'price'=>$goods_setmeal_detail['price'],
                    'create_time'=>time()
                ];
                //ceshi123
                $setmeal_id = GoodsSetmeal::insertGetId($add_goods_setmeal_data);//商品套餐ID
                //商品套餐详情
                foreach($goods_spec_details as $goods_spec_detail){
                    $add_goods_spec_data = [
                        'lease_time'=>$goods_spec_detail['lease_time'],
                        'setmeal_id'=>$setmeal_id,
                        'lease_price'=>$goods_spec_detail['lease_price'],
                        'withhold_cycle'=>$goods_spec_detail['withhold_cycle'],
                        'day_price'=>$goods_spec_detail['day_price'],
                        'goods_id'=>$goods_id
                    ];

                    //ceshi123
                    $spec_id = GoodsSpec::insert($add_goods_spec_data);//商品套餐ID
                }
//                $spec_id=1;
                //订单
                $add_order_data = [
                    'seller_id'=>$otherMember['is_shop']?$otherMember['member_id']:'1678175782',
                    'username'=>$isSendOther?'admin':'tingxiangzu',
                    'uid'=>$uid,
                    'trade_no'=>$order_data['trade_no'],
                    'is_insurance_choose'=>$order_data['is_insurance_choose'],
                    'is_latest_performance_time'=>$order_data['is_latest_performance_time'],
                    'rent_total'=>$order_data['rent_total'],
                    'month_total'=>$order_data['month_total'],
                    'amount'=>$order_data['amount'],
                    'payment'=>$order_data['payment'],
                    'remark'=>$order_data['remark'],
                    'realname'=>$order_data['realname'],
                    'mobile'=>$order_data['mobile'],
                    'address'=>$order_data['address'],
                    'pay_time'=>$order_data['pay_time'],
                    'prov'=>$order_data['prov'],
                    'city'=>$order_data['city'],
                    'area'=>$order_data['area'],
                    'begin_time'=>date('Y-m-d H:i:s'),
                    'end_time'=>date('Y-m-d H:i:s',strtotime('+ '.$order_data['month_total'].'month')),
                    'payer_user_id'=>$order_data['payer_user_id'],
                    'user_email'=>$order_data['user_email'],
                    'old_order_id'=>$order_data['id'],
                    'status'=>OrderService::ORDER_STATUS_SIGN_NOCHECK,
                    'create_time'=>time(),
                    'update_time'=>time(),
                    'pay_type'=>'1',
                    'order_from'=>'tingxiangzu-'.$order_data['order_from'],
                    'foregift_deduct'=>$order_data['foregift_deduct'],
                    'foregift_pay'=>$order_data['foregift_pay']
                ];
                //ceshi123
                $order_id = Order::insertGetId($add_order_data);//订单ID
//                dd($order_id);
                //ceshi123
               $res_set = RadarService::setOtherOrder($order_count,$order_data['id']);
                //风控备注
                if($remark_data){
                    foreach($remark_data as $remark_value){
                        $add_remark_data = [
                            'uid'=>'23',
                            'username'=>'同步',
                            'create_time'=>time(),
                            'remark'=>$remark_value['remark'].'(风控建议)',
                            'order_id'=>$order_id
                        ];
                        OrderRemark::insert($add_remark_data);
                    }
                }

                $add_remark = [
                    'uid'=>'23',
                    'username'=>'同步',
                    'create_time'=>time(),
                    'remark'=>'同步订单',
                    'order_id'=>$order_id
                ];
                OrderRemark::insert($add_remark);

                if($isSendOther==1){
                    $add_remark = [
                        'uid'=>'23',
                        'username'=>'同步',
                        'create_time'=>time(),
                        'remark'=>'订单已推给其他平台'.$otherMember['name_tit'],
                        'order_id'=>$order_id
                    ];
                    OrderRemark::insert($add_remark);
                }else{
                    $member = MemberOther::where('id',$uid)->select('cert_name','cert_no','mobile','id')->first();
                    $member=obToArray($member);
//                    YpcreditService::query($member,$order_id);
                }
                //订单商品
                $add_order_goods_data = [
                    'order_id'=>$order_id,
                    'goods_id'=>$goods_id,
                    'goods_title'=>$order_data['goods_title'],
                    'imgurl'=>$order_data['imgurl'],
                    'setmeal_id'=>$setmeal_id,
                    'setmeal_title'=>$order_data['setmeal_title'],
                    'spec_id'=>$spec_id,
                    'lease_set'=>$order_data['lease_set'],
                    'lease_time'=>$order_data['lease_time'],
                    'lease_price'=>$order_data['lease_price'],
                    'setmeal_price'=>$order_data['setmeal_price'],
                    'setmeal_foregift'=>$order_data['setmeal_foregift'],
                    'start_date'=>$order_data['start_date'],
                    'pact_type'=>$order_data['pact_type'],
                    'is_buy_out'=>$order_data['is_buy_out'],
                    'create_time'=>$order_data['create_time'],
                    'device_number'=>$order_data['device_number'],
                    'website_price'=>$order_data['website_price'],
                    'seller_id'=>'1687342445'
                ];
                //ceshi123
                OrderGoods::insert($add_order_goods_data);

                //订单租期
//                foreach($order_lease_datas as $order_lease_data){
//                    $add_order_lease_data = [
//                        'order_id'=>$order_id,
//                        'which_period'=>$order_lease_data['which_period'],
//                        'rent'=>$order_lease_data['rent'],
//                        'begin_time'=>$order_lease_data['begin_time'],
//                        'end_time'=>$order_lease_data['end_time'],
//                        'create_time'=>$order_lease_data['create_time']
//                    ];
//                    //ceshi123
//                    //OrderLease::insert($add_order_lease_data);
//                }
                //订单租期下单日开始算
                $add_order_data['lease_time']=$order_data['lease_time'];
                OrderLease::createOtherOrderLease($add_order_data,$order_id,$order_lease_datas);
                $authenticLog = AuthenticLog::where('order_id',$order_id)->select('id')->first();
                $authenticLog = obToArray($authenticLog);
                if($authenticLog){
                    //已有认证资料

                }else{
                    //认证资料
                    $add_authentic_data = [
                        'order_id'=>$order_id,
                        'certify_id'=>'1',
                        'status'=>'1',
                        'cert_no'=>$cert_no,
                        'cert_name'=>$member_data['cert_name'],
                        'idcard_front'=>$member_data['idcard_front'],
                        'idcard_back'=>$member_data['idcard_back'],
                        'create_time'=>date('Y-m-d H:i:s')
                    ];
                    //ceshi123
                    AuthenticLog::insert($add_authentic_data);
                }
                Redis::set('TradeNo'.$order_data['trade_no'],1);
              }
            var_dump($order_id);
            exit();
            dd($order_id);


            }
            $this->infoLog('订单同步任务执行成功',$res['data']);

        }else{ //提示

            $this->infoLog('订单同步任务执行失败',[$res['msg']]);
        }

    }

    public function upload_img($fileName){
        $fileUrl = 'https://img.tingxiangzu.com/'.$fileName;
        // echo $fileUrl;
        // dd(file_exists($fileUrl));
        if(!empty($fileName)){
        // echo $fileUrl."\r\n";
            $file = file_get_contents($fileUrl);
            $path = dirname(dirname(dirname(dirname(__FILE__)))) . '/storage/tmp/'.$fileName;

            file_put_contents($path,$file);
            $uploud_res = AlipayService::upload($fileName,$path);
            // print_r($uploud_res);
            // dd($uploud_res);
            if($uploud_res['status']){
                if(file_exists($path)){
                    unlink($path);
                }
            }
        }

    }
}
